import { DollarOutlined, ArrowUpOutlined, ArrowDownOutlined, RiseOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Table, DatePicker, Select, Button, Space } from 'antd';

import { financeApi } from '../../api/financeApi';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default function FinanceOverview() {
  const [loading, setLoading] = useState(false);
  const [overviewData, setOverviewData] = useState({});
  const [incomeData, setIncomeData] = useState([]);
  const [expenseData, setExpenseData] = useState([]);
  const [dateRange, setDateRange] = useState([dayjs().subtract(30, 'day'), dayjs()]);
  const [period, setPeriod] = useState('month');

  useEffect(() => {
    fetchData();
  }, [dateRange, period]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [overview, income, expense] = await Promise.all([
        financeApi.getFinanceOverview(),
        financeApi.getIncomeStatistics({ 
          startDate: dateRange[0].format('YYYY-MM-DD'),
          endDate: dateRange[1].format('YYYY-MM-DD'),
          period 
        }),
        financeApi.getExpenseStatistics({ 
          startDate: dateRange[0].format('YYYY-MM-DD'),
          endDate: dateRange[1].format('YYYY-MM-DD'),
          period 
        })
      ]);
      setOverviewData(overview.data);
      setIncomeData(income.data);
      setExpenseData(expense.data);
    } catch (error) {
      console.error('获取财务数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const incomeColumns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '收入类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => `¥${amount.toLocaleString()}`,
    },
    {
      title: '项目',
      dataIndex: 'project',
      key: 'project',
    },
  ];

  const expenseColumns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '支出类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => `¥${amount.toLocaleString()}`,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24 }}>
        <Space>
          <RangePicker
            value={dateRange}
            onChange={setDateRange}
            style={{ width: 240 }}
          />
          <Select
            value={period}
            onChange={setPeriod}
            style={{ width: 120 }}
          >
            <Option value="day">按日</Option>
            <Option value="week">按周</Option>
            <Option value="month">按月</Option>
            <Option value="quarter">按季</Option>
          </Select>
          <Button type="primary" onClick={fetchData}>
            刷新数据
          </Button>
        </Space>
      </div>

      <div style={{ overflowX: 'auto', marginBottom: 24 }}>
        <div style={{ display: 'flex', minWidth: 'max-content' }}>
          <div style={{ minWidth: '200px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总收入"
                value={overviewData.totalIncome || 0}
                prefix={<DollarOutlined />}
                valueStyle={{ color: '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
                suffix="元"
              />
            </Card>
          </div>
          <div style={{ minWidth: '200px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总支出"
                value={overviewData.totalExpense || 0}
                prefix={<DollarOutlined />}
                valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                suffix="元"
              />
            </Card>
          </div>
          <div style={{ minWidth: '200px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="净利润"
                value={overviewData.netProfit || 0}
                prefix={<RiseOutlined />}
                valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
                suffix="元"
              />
            </Card>
          </div>
          <div style={{ minWidth: '200px' }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="现金流"
                value={overviewData.cashFlow || 0}
                prefix={<ArrowUpOutlined />}
                valueStyle={{ color: '#722ed1', fontSize: '24px', fontWeight: 'bold' }}
                suffix="元"
              />
            </Card>
          </div>
        </div>
      </div>

      <Row gutter={16}>
        <Col span={12}>
          <Card title="收入明细" loading={loading}>
            <Table
              columns={incomeColumns}
              dataSource={incomeData}
              pagination={{ pageSize: 10 }}
              size="small"
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="支出明细" loading={loading}>
            <Table
              columns={expenseColumns}
              dataSource={expenseData}
              pagination={{ pageSize: 10 }}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}
